import cheerio from 'react-native-cheerio';
import util from 'util';

import Book from "./entity/Book";
import Chapter from "./entity/Chapter";
import Content from "./entity/Content";

import tool from '../utils/tool';
import http from '../utils/http';

let URL_SEARCH = "https://www.biquge9.cc/s.php?q=%s";
let URL_HOME = "https://www.biquge9.cc";

const search = (keyword) => {
    let fetch_promise = new Promise(async (resolve, reject) => {
        try {
            let url = util.format(URL_SEARCH, encodeURIComponent(keyword));
            let response = await fetch(url);
            const $ = cheerio.load(await response.text());
            let books = $('.bookbox').map(function (i, el) {
                let x = $(this).html();
                let title = $('.bookname a', this).text();
                let href = $('.bookname a', this).attr('href');
                let author = $('.author', this).text();
                let book = new Book(href, title, author);
                book.source = api.id;
                return book;
            });
            let arr = tool.toArray(books);
            resolve(arr);
        } catch (e) {
            reject(e);
        }
    });

    return new Promise(async (resolve, reject) => {
        http.fetchWithTimeout(fetch_promise)
            .then(res => resolve(res))
            .catch(err => reject(err))
        ;
    });
};

const chapters = (bookId) => {
    let fetch_promise = new Promise(async (resolve, reject) => {
        fetch(bookId)
            .then(res => {
                return res.blob().then(blob => tool.readBlobAsText(blob, "UTF-8"));
                // return res.text();
            })
            .then(data => {
                const $ = cheerio.load(data);
                let chapters = $('.listmain dd a').map(function (i, el) {
                    let href = $(this).attr('href');
                    let text = $(this).text();
                    let c = new Chapter(text, href);
                    return c;
                });
                let arr = tool.toArray(chapters);
                resolve(arr);
            }).catch(err => {
            reject(err);
        });
    });

    return new Promise(async (resolve, reject) => {
        http.fetchWithTimeout(fetch_promise)
            .then(res => resolve(res))
            .catch(err => reject(err))
        ;
    });
};

const content = (link) => {
    let fetch_promise = new Promise(async (resolve, reject) => {
        fetch(link).then(res => {
            return res.blob().then(blob => tool.readBlobAsText(blob, "UTF-8"));
            // return res.text();
        }).then(data => {
            const $ = cheerio.load(data, {decodeEntities: false});
            let title = $('.content h1').text(),
                body = $('#content').html();
            body = tool.replace(body, '<br>', '\n');
            body = tool.replace(body, '&nbsp;', '');
            body = tool.replace(body, '\u3000\u3000', '');
            body = tool.replace(body, '　　　　', '');
            body = tool.replace(body, '    ', '');
            body = tool.replace(body, '请记住本书首发域名：www.biquge9.cc。笔趣阁手机版更新最快网址：m.biquge9.cc', '');
            body = tool.replace(body, '\n\n', '\n');
            let c = new Content(title, body);
            resolve(c);
        }).catch(err => {
            reject(err);
        });
    });

    return new Promise(async (resolve, reject) => {
        http.fetchWithTimeout(fetch_promise)
            .then(res => resolve(res))
            .catch(err => reject(err))
        ;
    });
};

const api = {
    id: 'biquge9.cc',
    name: '笔趣阁(biquge9.cc)',
    homepage: URL_HOME,
    search: search,
    chapters: chapters,
    content: content
};

export default api;